/**
 *  iBizSys 5.0 机器人生产代码（不要直接修改当前代码）
 *  http://www.ibizsys.net
 */
package com.sa.litetwo.app.card.controller;

import net.ibizsys.paas.util.GlobalContext;
import net.ibizsys.paas.util.StringHelper;
import net.ibizsys.paas.util.spring.IBizOverride;
import net.ibizsys.paas.web.AjaxActionResult;
import net.ibizsys.paas.web.MDAjaxActionResult;
import net.ibizsys.paas.web.WebConfig;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.wltea.analyzer.lucene.IKAnalyzer;

import net.ibizsys.paas.appmodel.AppModelGlobal;
import net.ibizsys.paas.appmodel.IApplicationModel;
import net.ibizsys.paas.demodel.DEModelGlobal;
import net.ibizsys.paas.demodel.IDataEntityModel;
import net.ibizsys.paas.service.IService;
import net.ibizsys.paas.service.ServiceGlobal;
import net.ibizsys.paas.sysmodel.ISystemModel;
import net.ibizsys.paas.sysmodel.SysModelGlobal;
import net.ibizsys.paas.controller.ViewControllerGlobal;
import net.ibizsys.paas.core.Errors;
import net.ibizsys.paas.ctrlmodel.ICtrlModel;
import net.ibizsys.paas.db.SelectCond;
import net.ibizsys.paas.ctrlhandler.ICtrlHandler;

import com.sa.litetwo.srv.liteTwoSysModel;
import com.sa.litetwo.srv.card.entity.GG_CARD;
import com.sa.litetwo.srv.card.service.GG_CARDService;
import com.sa.litetwo.srv.card.service.USRGG_CARDService;

import freemarker.core.ParseException;

import com.sa.litetwo.app.AppAppModel;

@Controller
@IBizOverride
public class USRGG_CARDFullSearchViewController extends GG_CARDFullSearchViewController
{
	public USRGG_CARDFullSearchViewController() throws Exception
	{
	}

	protected AjaxActionResult onViewAjaxAction(String strAction) throws Exception
	{
		/**
		 * 查询controler
		 */

		if (StringHelper.compare("fs", strAction, true) == 0)
		{
			MDAjaxActionResult ajaxResult = new MDAjaxActionResult();
			String kerwords = this.getWebContext().getPostValue("kw");
			String arr = this.getWebContext().getPostValue("ids");
			String currentPage = this.getWebContext().getPostValue("nowpage");
			int s = Integer.valueOf(currentPage);
			int pageSize = 25;
		 
			 
			MDAjaxActionResult result = this.SearchByPage(new String[]{"GG_CARD"}, kerwords, "index", s, pageSize,true);
			ArrayList<Map<String, String>> list = (ArrayList<Map<String, String>>) result.getUserObject();
			System.out.println("返回结果集合" + list.size());
			Map<String, Integer> map = new HashMap<String, Integer>();
			JSONArray json = new JSONArray();
			for (Map<String, String> o : list)
			{
				if (o.containsKey("numberpage") == false)
				{
					String type = (String) o.get("type");
					String title = (String) o.get("title");
					String desc = (String) o.get("desc");
					String updatedate = (String) o.get("updatedate");
					String key = (String) o.get("key");
					JSONObject jo = new JSONObject();
					jo.put("type", type);
					jo.put("title", title);
					jo.put("desc", desc);
					jo.put("updatedate", updatedate);
					jo.put("key", key);
					jo.put("tag", (String) o.get("tag"));
					json.put(jo);
					if (map.containsKey(type))
					{
						map.put(type, map.get(type).intValue() + 1);
					}
					else
					{
						map.put(type, 1);
					}

				}
			}
			int numberpage = result.getPageSize();
			int totalhits = result.getTotalRow();
			ajaxResult.setExtAttr("result", json);
			ajaxResult.setExtAttr("page", s);
			ajaxResult.setExtAttr("numberpage", numberpage);
			ajaxResult.setExtAttr("totalhits", totalhits);
			return ajaxResult;
		}
		else if (StringHelper.compare("mk", strAction, true) == 0)
		{
			MDAjaxActionResult ajaxResult = new MDAjaxActionResult();
			USRGG_CARDService service=(USRGG_CARDService)GG_CARDService.getInstance();
			ArrayList<GG_CARD> list=service.select(new SelectCond());
			for(GG_CARD card:list)
			{
				service.index(card);
			}
			
			ajaxResult.setExtAttr("stadus", "Worwed");
			return ajaxResult;
			/**
			 * 创建索引
			 */
		}
		else
		{
			return super.onViewAjaxAction(strAction);
		}
	}
	
	
	public String exChangeKeyWord(String strKeyword)
	{
		String strNewKeyWord = "";

		strKeyword = strKeyword.replaceAll("　", " ");
		strKeyword = strKeyword.trim();
		try
		{
			int x = 0;
			while (strKeyword.indexOf("  ") >= 0)
			{
				strKeyword = strKeyword.replace("  ", " ");
				x++;
				if (x > 10)
					break;
			}
			x = 0;
			while (strKeyword.indexOf(" +") >= 0)
			{
				strKeyword = strKeyword.replace(" +", "+");
				x++;
				if (x > 10)
					break;
			}
			x = 0;
			while (strKeyword.indexOf("+ ") >= 0)
			{
				strKeyword = strKeyword.replace("+ ", "+");
				x++;
				if (x > 10)
					break;
			}

			String[] keyItems = strKeyword.split("[ ]");
			if (keyItems.length > 1 || strKeyword.indexOf("+") > 0)
			{
				strNewKeyWord = "(";
				for (int i = 0; i < keyItems.length; i++)
				{
					if (StringHelper.isNullOrEmpty(keyItems[i]))
						continue;
					if (i != 0)
						strNewKeyWord += " OR ";

					String strTmp = keyItems[i];
					if (strTmp.startsWith("+") != true && strTmp.endsWith("+") != true && strTmp.indexOf("+") > 0)
					{
						String[] keyItemsAdd = strTmp.split("[+]");

						if (keyItemsAdd.length > 1)
						{
							strNewKeyWord += " ( ";
							for (int j = 0; j < keyItemsAdd.length; j++)
							{
								if (StringHelper.isNullOrEmpty(keyItemsAdd[j]))
									continue;
								if (j != 0)
									strNewKeyWord += " AND ";

								strNewKeyWord += keyItemsAdd[j];
							}
							strNewKeyWord += " ) ";
						}
						else
							strNewKeyWord += strTmp;

					}
					else
						strNewKeyWord += keyItems[i];
				}
				strNewKeyWord += ")";
			}
			else
				strNewKeyWord = strKeyword;
		}
		catch (Exception ex)
		{
			strNewKeyWord = strKeyword;
		}
		return strNewKeyWord;
	}
	public List<Map<String, String>> Search(String keywords,String field) throws Exception, IOException, ParseException,InvalidTokenOffsetsException
	{
	 
		String test="";
		
		 
		
		String[] hitsmulu = test.split(",");
		return (ArrayList<Map<String, String>>) SearchByPage(hitsmulu, keywords,field, 1, 100, false).getUserObject();

	}
	
	public MDAjaxActionResult SearchByPage(String[] indexdir, String keywords, String field,int currentPage, int pageSize, boolean bHightText) throws Exception,IOException,ParseException, InvalidTokenOffsetsException
	{

		MDAjaxActionResult result = new MDAjaxActionResult();
		ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();
		result.setUserObject(list);
		Vector<IndexReader> readers = new Vector<IndexReader>();
		MultiReader m = null;
		Query query = null;
		Analyzer analyzer =  this.getAnalyzer();
		try
		{
		

			for (int i = 0; i < indexdir.length; i++)
			{	
				String BasicDirectory=WebConfig.getCurrent().getAttribute("INDEXPATH", "C://index//");
				System.out.println("主目录分页"+BasicDirectory);
				String strISFolder = BasicDirectory+ indexdir[i];
				System.out.println("strISFolder主要目录下面的小目录"+strISFolder);
				try
				{
					IndexReader reader = IndexReader.open(FSDirectory.open(new File(strISFolder))); // only
					readers.add(reader);
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
			IndexReader[] arr = new IndexReader[readers.size()];
			System.out.println("readers.size()"+readers.size());
			readers.toArray(arr);
			m = new MultiReader(arr);
			IndexSearcher indexsearch2 = new IndexSearcher(m);
			QueryParser queryparser = new QueryParser(Version.LUCENE_41, field, analyzer);
			queryparser.setDefaultOperator(queryparser.OR_OPERATOR);
			TopScoreDocCollector topscoredoccollector = TopScoreDocCollector.create(currentPage * pageSize, false);

			keywords = this.exChangeKeyWord(keywords);
			query = queryparser.parse(keywords);
			BooleanQuery.setMaxClauseCount(3072);

			indexsearch2.search(query, topscoredoccollector);
			int totalhits = topscoredoccollector.getTotalHits();
			int numberpage = (totalhits % pageSize == 0) ? (totalhits / pageSize) : (totalhits / pageSize + 1);// 此处为统计页数，
			int begin = pageSize * (currentPage - 1);
			// 查询其实记录位置
			int end = Math.min(begin + pageSize, totalhits);
			// 查询终止记录位置
			TopDocs tds = topscoredoccollector.topDocs(begin, end);
			ScoreDoc[] sd = tds.scoreDocs;
			for (int i = 0; i < sd.length; i++)
			{
				Map<String, String> map = new HashMap<String, String>();
				Document doc = indexsearch2.doc(sd[i].doc);
				String text = doc.get("title");
				if (StringHelper.isNullOrEmpty(text))
					text = "信息";

				String text1 = doc.get("desc");
				if (StringHelper.isNullOrEmpty(text1))
					text1 = "无";

				map.put("tag", text + "|" + doc.get("type") + "|" + text1);

				if (bHightText)
				{

					SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<font color='red'>", "</font>");

					Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(query));

					TokenStream tokenStream = analyzer.tokenStream(field, new StringReader(text));
					String highLightText = highlighter.getBestFragment(tokenStream, text);
					if (highLightText != null)
						text = highLightText;

					TokenStream tokenStream1 = analyzer.tokenStream(field, new StringReader(text1));
					String highLightText1 = highlighter.getBestFragment(tokenStream1, text1);
					if (highLightText1 != null)
						text1 = highLightText1;

				}
				map.put("title", text);
				map.put("desc", text1);
				map.put("type", doc.get("type"));
				map.put("updatedate", doc.get("updatetime"));
				map.put("key", doc.get("key"));
				 
				list.add(map);
			}

		
			if(numberpage==0)
				numberpage=1;
			result.setPageSize(numberpage);
			result.setTotalRow(totalhits);

		}
		catch (ParseException e)
		{
			result.setRetCode(Errors.INPUTERROR);
			result.setErrorInfo(e.getMessage());

			e.printStackTrace();
		 
		}
		finally
		{
			
			try
			{
				for (IndexReader reader : readers)
				{
					reader.close();
				}
			 
			}
			catch (Exception ex)
			{

			} 
			try
			{
				 
				m.close();
			}
			catch (Exception ex)
			{

			} 
		}

		return result;
	}
	
	public synchronized Analyzer getAnalyzer()
	{
		if (GlobalContext.getCurrent().getValue("IKAnalyzer") == null)
		{
			Analyzer analyzer = new IKAnalyzer(true);//search的分词器，用的是智能模式，环境中没有那个maker的标记
			GlobalContext.getCurrent().setValue("IKAnalyzer", analyzer);
			return analyzer;
		}
		else
		{
			return (Analyzer) GlobalContext.getCurrent().getValue("IKAnalyzer");
		}
	}
}